{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a6edc8f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "def detect_lane_lines(image_path):\n",
    "    # 读取图像\n",
    "    image = cv2.imread(image_path)\n",
    "    # 获取原始图像的高度和宽度\n",
    "    original_height, original_width = image.shape[:2]\n",
    "    # 定义缩放比例\n",
    "    scale = 0.5\n",
    "    new_width = int(original_width * scale)\n",
    "    new_height = int(original_height * scale)\n",
    "    # 转换为灰度图像减少计算\n",
    "    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n",
    "    # 进行高斯模糊，减少噪声影响\n",
    "    blurred = cv2.GaussianBlur(gray, (5, 5), 0)\n",
    "    # 使用Canny边缘检测算法获取边缘\n",
    "    edges = cv2.Canny(blurred, 50, 150)\n",
    "    # 定义感兴趣区域（ROI），制造掩膜\n",
    "    height, width = edges.shape\n",
    "    mask = np.zeros_like(edges)\n",
    "    # 围绕中间黄线定义一个ROI\n",
    "    offset = 200  \n",
    "    polygon = np.array([[\n",
    "        (width / 2 - offset, height), #左下角顶点\n",
    "        (width / 2 - offset, height / 4), #左上角顶点\n",
    "        (width / 2 + offset, height / 4), #右上角顶点\n",
    "        (width / 2 + offset, height)  #右下角顶点\n",
    "    ]], np.int32)\n",
    "    cv2.fillPoly(mask, polygon, 255)\n",
    "    \n",
    "    #提取出感兴趣部分的边缘图像\n",
    "    masked_edges = cv2.bitwise_and(edges, mask)\n",
    "\n",
    "    # 使用霍夫变换检测直线\n",
    "    lines = cv2.HoughLinesP(masked_edges, 1, np.pi / 180, 30, minLineLength=100, maxLineGap=20)\n",
    "\n",
    "    # 在原图像上绘制检测到的车道线（用绿色绘制）\n",
    "    if lines is not None:\n",
    "        for line in lines:\n",
    "            x1, y1, x2, y2 = line[0]\n",
    "            cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 2)\n",
    "\n",
    "    # 对最终要显示的图像进行缩放\n",
    "    resized_image = cv2.resize(image, (new_width, new_height))\n",
    "\n",
    "    return resized_image\n",
    "    # 返回处理后的图像，即包含绘制了检测到的车道线并且经过缩放后的图像。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0fb542bb",
   "metadata": {},
   "outputs": [],
   "source": [
    "image_path = \"example.jpg\"\n",
    "result_image = detect_lane_lines(image_path) #处理图像\n",
    "cv2.imshow(\"Lane Lines Detection\", result_image) #显示图像\n",
    "cv2.imwrite(\"result_image.jpg\", result_image) #存图像\n",
    "cv2.waitKey(0)   #按键就继续\n",
    "cv2.destroyAllWindows()   #关掉窗口"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "DL",
   "language": "python",
   "name": "dl"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
